import { login, profile, loginOut } from './api'

export default {
  namespaced: true,
  state: () => ({
    user: {}
  }),
  getters: {
    logined (state) {
      return state.user.id > 0
    },
    user (state) {
      return state.user
    },
    avatar (state) {
      return state.user.avatar ? state.user.avatar.url : 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'
    },
    isSuper (state) {
      return state.user.is_super
    }
  },
  actions: {
    async token ({ commit, dispatch }, params) {
      try {
        await login(params)
        dispatch('profile')
      } catch (e) {
        commit('LOGIN_OUT')
        throw e
      }
    },
    async profile ({ commit }) {
      const { data } = await profile()
      commit('SET_USER', data)
    },
    async loginOut ({ commit }) {
      await loginOut()
      commit('LOGIN_OUT')
    }
  },
  mutations: {
    SET_USER (state, payload) {
      state.user = payload.data
    },
    LOGIN_OUT (state) {
      state.user = {}
    }
  }
}
